package sms

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"net/http"
	"github.com/axgle/mahonia"
)

var (
	smsUrl   = "http://221.179.180.158:9007/QxtSms/QxtFirewall" 
	operID = "dflcjs"
	operPass = "dew12ss*22"
)

/*
  两种方式本质是一样的吗？ 
func SendSMS(mobile, content string) (respCode string, err error) {
    url := fmt.Sprintf("%s?OperID=%s&OperPass=%s&SendTime=&ValidTime=&AppendID=&DesMobile=%s&Content=%s&ContentType=15", smsUrl,operID,operPass,mobile,content)
    request, _ := http.NewRequest("POST", url, nil)
    request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    //request.Header.Set("Content-Length", fmt.Sprintf("%d", len(b)))
    client := &http.Client{}
    resp, err := client.Do(request)
    if err != nil {
        // 处理错误
    }
    defer resp.Body.Close()
    data, err := parseSmsResp(resp)
    if err != nil || data.StatusCode != "000000" {
        // 处理错误
    }
}
*/

func SendSMS(mobile, content string) (respCode string, err error) {
    // utf-8 to gbk
	enc :=mahonia.NewEncoder("gbk")
	gbkStr := enc.ConvertString(content)
	urlEncStr := url.QueryEscape(gbkStr)
	v := make(url.Values)
	v.Set("OperID", operID)
	v.Set("OperPass", operPass)
	//v.Set("SendTime", c)        //发送时间:为空表示立即发送
	//v.Set("ValidTime", c)       //消息存活有效期
	v.Set("AppendID", "0")
	v.Set("DesMobile", mobile)
	v.Set("Content", urlEncStr)
	v.Set("ContentType", "15")
	rsp, err := http.PostForm(smsUrl, v)
	if err != nil {
		fmt.Println(err)
	}
	defer rsp.Body.Close()
	bodyByte, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		fmt.Println(err)
	}
	respCode = string(bodyByte)
	return
}
